package kalender.backend;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;


public class LuserPic {
	private Luser uid;
	private byte[] picture;
	
	public Luser getUid() { return uid; }
	public void setUid(Luser l) { uid = l; }

	public byte[] getPicture() { return picture; }
	public void setPicture(byte[] p) { picture = p; }
	
	public static LuserPic findByUser(Luser l) throws BackendException {
		Connection conn = DatabaseManager.getConnection();
		try {
			PreparedStatement ps = conn.prepareStatement("select * from luserpic where uid = ?");
			ps.setInt(1, l.getUid());
			ResultSet rs = ps.executeQuery();
			SQLWarning warn1 = ps.getWarnings();
			DatabaseManager.printWarning(warn1);
			SQLWarning warn2 = rs.getWarnings();
			DatabaseManager.printWarning(warn2);
			if (rs.next()) {
				LuserPic lp = new LuserPic();
				int u = rs.getInt("uid");
				lp.uid = Luser.find(u);
				lp.picture = rs.getBytes("picture");
				return lp;
			} else {
				return null;
			}
		} catch (SQLException e) {
			DatabaseManager.printException(e);
			throw new BackendException("Databasfel. Var god försök igen.", e);
		}
	}
	
	public void saveNew() throws BackendException {
		Connection conn = DatabaseManager.getConnection();
		try {
			PreparedStatement ps = conn.prepareStatement("insert into luserpic (uid, picture) values(?, ?)");
			ps.setInt(1, uid.getUid());
			ps.setBytes(2, picture);
			ps.executeUpdate();
			SQLWarning warning = ps.getWarnings();
			DatabaseManager.printWarning(warning);
		} catch (SQLException e) {
			DatabaseManager.printException(e);
			throw new BackendException("Databasfel. Var god försök igen.", e);
		}
	}
	
	public void saveUpdate() throws BackendException {
		Connection conn = DatabaseManager.getConnection();
		try {
			PreparedStatement ps = conn.prepareStatement("update luserpic set picture = ? where uid = ?");
			ps.setBytes(1, picture);
			ps.setInt(2, uid.getUid());
			ps.executeUpdate();
			SQLWarning warning = ps.getWarnings();
			DatabaseManager.printWarning(warning);
		} catch (SQLException e) {
			DatabaseManager.printException(e);
			throw new BackendException("Databasfel. Var god försök igen.", e);
		}
	}
	
	public static void delete(int uid) throws BackendException {
		Connection conn = DatabaseManager.getConnection();
		try {
			PreparedStatement ps = conn.prepareStatement("delete from luserpic where uid = ?");
			ps.setInt(1, uid);
			ps.executeUpdate();
			SQLWarning warning = ps.getWarnings();
			DatabaseManager.printWarning(warning);
		} catch (SQLException e) {
			DatabaseManager.printException(e);
			throw new BackendException("Databasfel. Var god försök igen.", e);
		}
	}
}
